package com.example.diary

import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.example.diary.R
import kotlinx.android.synthetic.main.activity_login.*

class LoginActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        val prefs = getPreferences(Context.MODE_PRIVATE)
        val isRemember = prefs.getBoolean("remember_password", false)
        if (isRemember) {
            // 将账号和密码都设置到文本框中
            val account = prefs.getString("account", "")
            val password = prefs.getString("password", "")
            username.setText(account)
            et_password.setText(password)
            cb_choose.isChecked = true
        }

        logon.setOnClickListener {
            val account = username.text.toString()
            val password = et_password.text.toString()
            // 如果
            if (et_password.getText().toString().trim().equals("") || username.getText().toString().trim().equals("")){
                Toast.makeText(this, "用户名或者密码未填写", Toast.LENGTH_SHORT).show()
            }
            else if (prefs.getString(account,"").toString()!="") {
                Toast.makeText(this, "用户名已存在", Toast.LENGTH_SHORT).show()
            }

            else {

                val editor = prefs.edit()
                if (cb_choose.isChecked) { // 检查复选框是否被选中
                    editor.putBoolean("remember_password", true)
                    editor.putString("account", account)
                    editor.putString("password", password)

                    Toast.makeText(this, "注册成功！", Toast.LENGTH_SHORT).show()
                } else {
                    editor.clear()
                }
                editor.apply()
                val intent = Intent(this, LoginActivity::class.java)
                startActivity(intent)
                finish()
            }
        }



        login.setOnClickListener {
            val account = username.text.toString()
            val password = et_password.text.toString()
            val prefs2 = getPreferences(Context.MODE_PRIVATE)
            val aa=prefs2.getString("password","")

            if (et_password.getText().toString().trim().equals("") || username.getText().toString().trim().equals("")){
                Toast.makeText(this, "用户名或者密码未填写", Toast.LENGTH_SHORT).show()
            }
            else if(password.toString() != prefs2.getString("password","")) {
                Toast.makeText(this, "用户名或者密码错误", Toast.LENGTH_SHORT).show()
            }
            else
            {
                Toast.makeText(this, "登陆成功！", Toast.LENGTH_SHORT).show()
                val intent = Intent(this, MainActivity::class.java)
                startActivity(intent)
            }


        }
    }

}